using System.Linq;
using System.Web;

namespace EOSCRM.Controls
{
    /// <summary>
    /// Summary description for SessionManager
    /// </summary>
    public class SessionManager
    {
        public static void AddRemovableSessionKey(string sessionKey)
        {
            if (HttpContext.Current.Session[SessionKeyForGrid.REMOVABLE_SESSION_KEYS] == null)
            {
                HttpContext.Current.Session[SessionKeyForGrid.REMOVABLE_SESSION_KEYS] = sessionKey;
                return;
            }

            var sessionKeys = HttpContext.Current.Session[SessionKeyForGrid.REMOVABLE_SESSION_KEYS].ToString().Split(',');
            if(!sessionKeys.Any())
            {
                HttpContext.Current.Session[SessionKeyForGrid.REMOVABLE_SESSION_KEYS] = sessionKey;
                return;
            }

            var newValue = sessionKeys.Where(key => key != sessionKey).Aggregate("", (current, key) => current + (key + ","));
            newValue += sessionKey;

            HttpContext.Current.Session[SessionKeyForGrid.REMOVABLE_SESSION_KEYS] = newValue;
        }

        public static void RemoveRemovableSessionKey(string sessionKey)
        {
            if (HttpContext.Current.Session[SessionKeyForGrid.REMOVABLE_SESSION_KEYS] == null)
                return;

            var sessionKeys = HttpContext.Current.Session[SessionKeyForGrid.REMOVABLE_SESSION_KEYS].ToString().Split(',');

            var newValue = sessionKeys.Where(key => key != sessionKey).Aggregate("", (current, key) => current + (key + ","));

            if (newValue.Length > 0)
                newValue = newValue.Substring(0, newValue.Length - 1);

            HttpContext.Current.Session[SessionKeyForGrid.REMOVABLE_SESSION_KEYS] = newValue == "" ? null : newValue;
        }

        public static void RemoveSession(string sessionKey)
        {
            HttpContext.Current.Session.Remove(sessionKey);
            RemoveRemovableSessionKey(sessionKey);
        }

        public static void AddSession(string sessionKey, object data)
        {
            HttpContext.Current.Session[sessionKey] = data;
            AddRemovableSessionKey(sessionKey);
        }

        public static object SessionValue(string sessionKey)
        {
            return HttpContext.Current.Session[sessionKey];
        }

        public static void ClearRemovableSessionKeys()
        {
            if (HttpContext.Current.Session[SessionKeyForGrid.REMOVABLE_SESSION_KEYS] == null)
                return;

            var sessionKeys = HttpContext.Current.Session[SessionKeyForGrid.REMOVABLE_SESSION_KEYS].ToString().Split(',');
            foreach (var sessionKey in sessionKeys)
                RemoveSession(sessionKey);
        }
    }
}